﻿$.extend({

    UserManagementSiteCollGroups: {
        /*
        TestCrossSiteCollection: function () {

        var susername = "dev\\viet.nguyen";
        var soapEnv = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
        <soap:Body> \
        <GetGroupCollectionFromUser xmlns='http://schemas.microsoft.com/sharepoint/soap/directory/'> \
        <userLoginName>" + susername + "</userLoginName> \
        </GetGroupCollectionFromUser> \
        </soap:Body> \
        </soap:Envelope>";

        $.ajax({
        url: "http://devapp/dev/site1/_vti_bin/usergroup.asmx",
        type: "POST",
        async: false,
        dataType: "xml",
        data: soapEnv,
        complete: $.UserManagementSiteCollGroups.ProcessUsers,
        contentType: "text/xml; charset=\"utf-8\""
        });
        },

        ProcessUsers: function (xData, status) {

        $(xData.responseXML).find("Group").each(function () {

        alert($.UMUtilities.StringTrim($(this).attr("Name")));
        alert($.UMUtilities.StringTrim($(this).attr("Description")));
        alert($.UMUtilities.StringTrim($(this).attr("ID")));
        });
        },
        */
        LoadPage: function () {

            var jqxhr = $.get('html/ManageForm.html');
            jqxhr.success(function (data) {

                $('#ManageFormDialog').html(data);
                $.UserManagementSiteCollGroups.SetOnClickEvents();
                $.UserManagement.SetButtonStyle();
                $.UserManagement.SetGlobalClickEvents();
            });

            jqxhr.error(function () {
                alert('Failed to load edit form.');
            });

            var jqxhr = $.get('html/AddGroups.html');
            jqxhr.success(function (data) {

                $('#addGroupForm').html(data);
                $.UserManagementSiteCollGroups.SetOnClickEventsForAddGroup();
            });

            jqxhr.error(function () {
                alert('Failed to load add group form.');
            });
        },

        SetOnClickEvents: function () {

            // on Click event for adding/removing groups - Site Collection Group Management
            $('#btnAddItems').click(function () {
                $("#ManageFormTable").hide();
                $("#LoadingImage").show();
                $.UserManagementSiteCollGroups.AddUserToGroups($('#lblEntityName').html());
                $("#LoadingImage").hide();
                $("#ManageFormTable").show();
            });

            $('#btnRemoveItems').click(function () {
                $("#ManageFormTable").hide();
                $("#LoadingImage").show();
                $.UserManagementSiteCollGroups.RemoveUserFromGroups($('#lblEntityName').html());
                $("#LoadingImage").hide();
                $("#ManageFormTable").show();
            });
        },

        SetOnClickEventsForAddGroup: function () {

            $('#btnOpenSelectGroupOwner').click(function () {
                var opt = {
                    title: 'Select a User',
                    autoOpen: false,
                    height: 'auto',
                    width: 430,
                    resizable: false
                };
                $.UserManagementSiteCollGroups.PopulateGroupOwnerForm();
                $('#selectGroupOwnerForm').dialog(opt).dialog('open');
            });

            // on click event for opening Add Group form
            $('#btnCreateSiteCollectionGroup').click(function () {
                $.UserManagementSiteCollGroups.PopulateAddGroupForm();
            });

            $('#btnAddUserAsGroupOwner').click(function () {
                $('#txtBoxSelectedGroupOwner').val($("#lstBxAvailableGroupOwners").val());
                $('#selectGroupOwnerForm').dialog('close');
            });

            $('#btnCloseAddGroupDialog').click(function () {
                $('#txtBoxGroupName').val('');
                $('#txtAreaGroupDescription').val('');
                $('#txtBoxSelectedGroupOwner').val('');
                window.parent.jQuery('#addGroupForm').dialog('close');
            });

            $('#btnSaveNewGroup').click(function () {
                $.UserManagementSiteCollGroups.SaveNewGroup();
            });
        },

        LoadSiteCollectionsDropDown: function () {

            $('#ddlSiteCollectionsMainPage').empty();
            $('#ddlSiteCollectionsMainPage').append($('<option></option>').val("").text("-- Select --"));

            $.each(asites, function (val, text) {
                $('#ddlSiteCollectionsMainPage').append($('<option></option>').val(text["Url"]).text(text["Name"]));
            });

            $('#ddlSiteCollectionsMainPage').change(function () {
                if ($('#ddlSiteCollectionsMainPage').val() != "") {
                    $("#btnCreateSiteCollectionGroup").button();
                    $("#SiteCollGroupManagementMenu").show();
                    $.UserManagementSiteCollGroups.PopulateDataTable($('#ddlSiteCollectionsMainPage').val());
                }
                else {
                    $('#siteCollGroupListTable').dataTable().fnClearTable();
                }
            });
        },

        PopulateDataTable: function (siteUrl) {

            try {
                $.UserManagementSiteCollGroups.LoadPage();

                // Initialize Group(s) Data Table
                var arryGroups = $.UserManagementDA.GetAllGroups(siteUrl);
                $('#siteCollGroupListTable').dataTable().fnClearTable();
                var dt = $('#siteCollGroupListTable').DataTable();
                dt.clear().rows.add(arryGroups).draw();

                // Wire up the data table to handle row selection
                $("#siteCollGroupListTable tbody").delegate("tr", "click", function () {
                    var groupName = $("td:first", this).text();
                    var groupDescription = $("td:eq(1)", this).text();
                    $.UserManagementSiteCollGroups.PopulateFormPage(groupName, groupDescription, $('#ddlSiteCollectionsMainPage').val());
                });

                $("#siteCollGroupListTable td:first-child").addClass("nowrap");
            }
            catch (e) {
                alert(e);
            }
        },

        PopulateFormPage: function (groupName, description, siteUrl) {

            try {
                var groupUrl = $().SPServices.SPGetCurrentSite() + "/_layouts/people.aspx?MembershipGroupId=" + $.UserManagementSiteCollGroups.GetGroupIDBySiteCollection(groupName, siteUrl);
                $.UserManagementSiteCollGroups.RefereshUserLists(groupName, siteUrl);

                $('#EntityTypeTitle').text("Group Name:");
                $('#lblInstruction').text(instructions[0].Text);
                $('#AvailableListBoxTitle').text("Available Users");
                $('#AssignedistBoxTitle').text("Selected Users");

                $("#lblEntityName").text(groupName);
                $("#lblGroupDescription").text(description);
                $("#lblEntityUrlName").text("View Group Info");
                $("#lblEntityUrlName").attr("href", groupUrl);
                $('#GroupDescription').show();
                $('#ManageFormDialog').dialog('open');
            }
            catch (e) {
                alert(e);
            }
        },

        GetGroupIDBySiteCollection: function (groupName, siteUrl) {

            var groupInfo = [];
            groupInfo = $.UserManagementDA.GetGroupInfo(groupName, siteUrl);
            return groupInfo[0].GroupID;
        },

        RefereshUserLists: function (groupName, siteUrl) {

            $.UserManagement.ClearListBoxItems();
            $('#filterAvailableItems').val('Search for Users...');
            $('#filterSelectedItems').val('Search for Users...');

            var arryAllUsers = $.UserManagementDA.GetAllUsers();
            var arrySelectedUsers = $.UserManagementDA.GetAllUsersByGroup(groupName, siteUrl);
            var arryFilteredUsers = $.UserManagement.FilterAvailableUsers(arryAllUsers, arrySelectedUsers);

            $.UserManagementGroups.PopulateUserLists("#lstBxAvailableItems", arryFilteredUsers);
            $.UserManagementGroups.PopulateUserLists("#lstBxSelectedItems", arrySelectedUsers);

            $('#lstBxAvailableItems').filterByText($('#filterAvailableItems'), false);
            $('#lstBxSelectedItems').filterByText($('#filterSelectedItems'), false);

            $.UMUtilities.SetListBoxHeight("#lstBxAvailableItems");
            $.UMUtilities.SetListBoxHeight("#lstBxSelectedItems");
        },

        PopulateGroupOwnerForm: function () {

            $('#lstBxAvailableGroupOwners > option').remove();
            $('#filterAvailableGroupOwners').val('Search for Users...');

            var arryAllUsers = $.UserManagementDA.GetAllUsers();
            $.UserManagementGroups.PopulateUserLists("#lstBxAvailableGroupOwners", arryAllUsers);
            $('#lstBxAvailableGroupOwners').filterByText($('#filterAvailableGroupOwners'), false);
        },

        AddUserToGroups: function (groupName) {

            groupName = $.UMUtilities.DecodeText(groupName);

            if (groupName == null) {
                alert("No group selected.");
                return;
            }

            if ($("#lstBxAvailableItems").val() == null) {
                alert("You haven't selected any users to add.");
                return;
            }
            else {
                $('#lstBxAvailableItems option:selected').each(function () {
                    $.UserManagementDA.AddUserToGroup(groupName, $(this).val(), $('#ddlSiteCollectionsMainPage').val());
                    $('#lstBxSelectedItems').append($('<option></option>').val($(this).val()).text($(this).text()));
                });

                $("#lstBxAvailableItems option:selected").remove();
                $.UMUtilities.SetListBoxHeight("#lstBxSelectedItems");
                $.UMUtilities.SetListBoxHeight("#lstBxAvailableItems");
            }
        },

        RemoveUserFromGroups: function (groupName) {

            groupName = $.UMUtilities.DecodeText(groupName);

            if (groupName == null) {
                alert("No group selected.");
                return;
            }

            if ($("#lstBxSelectedItems").val() == null) {
                alert("You haven't selected any users to remove.");
                return;
            }
            else {
                $('#lstBxSelectedItems option:selected').each(function () {
                    $.UserManagementDA.RemoveUserFromGroup(groupName, $(this).val(), $('#ddlSiteCollectionsMainPage').val());
                    $('#lstBxAvailableItems').append($('<option></option>').val($(this).val()).text($(this).text()));
                });

                $("#lstBxSelectedItems option:selected").remove();
                $.UMUtilities.SetListBoxHeight("#lstBxSelectedItems");
                $.UMUtilities.SetListBoxHeight("#lstBxAvailableItems");
            }
        },

        PopulateAddGroupForm: function () {

            $.UserManagementSiteCollGroups.LoadUI();
            $.UserManagementSiteCollGroups.ClearNewGroupFormFields();
            $('#spnSiteCollection').html($('#ddlSiteCollectionsMainPage').val());

            var arr = $.UserManagementDA.GetRoleCollectionFromWeb();
            $.each(arr, function (val, text) {

                var chk = $('<input />', {
                    type: 'checkbox',
                    value: text.RoleName
                })

                var row = $('<tr />').append($('<td />').append(chk)).append($('<td style="width:272px" />').append(text.RoleName + " - " + text.Description));
                $('#permissionLevels').append(row);
            });

            $('#addGroupForm').dialog('open');
        },

        SaveNewGroup: function () {

            // check that at least one permission role is selected
            if (!$('#permissionLevels input[type="checkbox"]').is(':checked')) {
                alert("Please select at least one permission role.");
                return false;
            }

            if ($('#txtBoxGroupName').val() != '' && $('#txtBoxSelectedGroupOwner').val() != '') {

                var groupName = $('#txtBoxGroupName').val();
                var descr = $('#txtAreaGroupDescription').val();
                var groupOwner = $('#txtBoxSelectedGroupOwner').val();
                var siteUrl = $('#ddlSiteCollectionsMainPage').val();
                var oType = "user";

                // validate group name for special characters
                var characterReg = /^[A-Za-z\s\d=&-]+$/;
                if (!characterReg.test(groupName)) {
                    alert("No special characters allowed in the group name.");
                    return false;
                }

                if ($('#chkBxAllGroups').is(':checked')) {
                    $.each(asites, function (val, text) {
                        var groupInfo2 = $.UserManagementDA.GetGroupInfo(groupName, text.Url);
                        if (groupInfo2.length == 0) {
                            // save group across all site collections 
                            $.UserManagementDA.CreateGroup(groupName, groupOwner, descr, oType, text.Url);

                            // assign roles to group
                            $('#permissionLevels').find('input[type="checkbox"]:checked').each(function () {
                                $.UserManagementDA.AddGroupToRole(groupName, this.value, text.Url);
                            });
                        }
                    });
                }
                else {
                    var groupInfo = $.UserManagementDA.GetGroupInfo(groupName, siteUrl);
                    if (groupInfo.length == 0) {
                        // save group 
                        $.UserManagementDA.CreateGroup(groupName, groupOwner, descr, oType, siteUrl);

                        // assign roles to group
                        $('#permissionLevels').find('input[type="checkbox"]:checked').each(function () {
                            $.UserManagementDA.AddGroupToRole(groupName, this.value, siteUrl);
                        });

                        window.parent.jQuery('#addGroupForm').dialog('close');
                        $.UserManagementSiteCollGroups.InitializeDataTables($('#ddlSiteCollectionsMainPage').val());
                    }
                    else {
                        alert("Group name exists already.");
                    }
                }
            }
            else {
                alert("Please complete the required fields.");
            }
        },

        ClearNewGroupFormFields: function () {

            $('#permissionLevels tbody').empty();
            $('#txtBoxGroupName').val('');
            $('#txtAreaGroupDescription').val('');
            $('#txtBoxSelectedGroupOwner').val('');
        },

        LoadUI: function () {

            $('#btnOpenSelectGroupOwner').button();
            $('#btnAddUserAsGroupOwner').button();
            $('#btnRemoveUsersNewGroup').button();
            $('#btnAddUsersNewGroup').button();
            $('#btnCloseAddGroupDialog').button();
            $('#btnSaveNewGroup').button();
        }
    }
});